<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="店铺名称" prop="storeName">
        <el-input v-model="queryParams.storeName" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="工号" prop="mark">
        <el-input
          v-model="queryParams.mark"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工号" prop="mark">
        <el-date-picker
            v-model="queryParams.month"
            type="month"
            placeholder="选择月">
          </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          v-hasPermi="['business:arrange:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:arrange:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:arrange:edit']">修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="handleImport"
          v-hasPermi="['business:arrange:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:arrange:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classifyList" max-height="650px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属区域" align="center" prop="regionName" />
      <el-table-column label="所属门店" align="center" prop="storeName" />
      <el-table-column label="技师姓名" align="center" prop="userName" />
      <el-table-column label="工号" align="center" prop="jobNumber" />
      <!-- <el-table-column label="工号" align="center" prop="regionId" /> -->
      <el-table-column label="电话" align="center" prop="phoneNumber" />
      <el-table-column label="排班月份" align="center" prop="month" />
      <el-table-column label="全天班" align="center" prop="shiftCount">
        <template slot-scope="scope">
          <span v-if="scope.row.shiftCount.全天班">{{ scope.row.shiftCount.全天班 }}天</span>
          <span v-else>0天</span>
        </template>
      </el-table-column>
      <el-table-column label="早班" align="center" prop="shiftCount">
        <template slot-scope="scope">
          <span v-if="scope.row.shiftCount.早班">{{ scope.row.shiftCount.早班 }}天</span>
          <span v-else>0天</span>
        </template>
      </el-table-column>
      <el-table-column label="晚班" align="center" prop="shiftCount">
        <template slot-scope="scope">
          <span v-if="scope.row.shiftCount.晚班">{{ scope.row.shiftCount.晚班 }}天</span>
          <span v-else>0天</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" /> -->
      <!-- <el-table-column label="早班" align="center" prop="storeName" />
      <el-table-column label="晚班" align="center" prop="storeId" /> -->
      <el-table-column label="操作" fixed="right" align="center" class-name="fixed-width" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:arrange:edit']">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-news" @click="handleExamine(scope.row)">审核</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-sort" @click="handletbu(scope.row)"
            v-hasPermi="['business:arrange:synchronization']">同步
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-drawer :title="'排班'" :visible.sync="classes" size="80%" @close="close" :wrapperClosable="false">
      <div id="app">
        <div class="calender-class">
          <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="归属区域" prop="area">
              <el-select clearable v-model="form.area" @change="changeRegion" :disabled="title.includes('修改')">
                <el-option v-for="(item, index) of region" :key="index" :label="item.label" :value="item.value">{{
                  item.label }}</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="归属门店" prop="postion">
              <el-select clearable v-model="form.postion" @change="changeStore" :disabled="title.includes('修改')">
                <el-option v-for="(item, index) of store" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                  }}</el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="月份" prop="">
              <el-date-picker v-model="form.month" type="month" placeholder="选择月份" format="yyyy年 MM月"
                value-format="yyyy-MM" @change="changeMonth">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="员工姓名" prop="userIds">
              <el-select clearable v-model="form.userIds" @change="changeTechnician" multiple collapse-tags
                :disabled="title.includes('修改')">
                <el-option v-for="(item, index) of technician" :key="index" :label="item.value" :value="item.key">{{
                  item.value }}</el-option>
              </el-select>
            </el-form-item>

          </el-form>
          <div class="setting">
            <div class="demo-drawer__content">
              <el-form :model="addForm">
                <el-form-item label="班次：" label-width="80px">
                  <el-radio-group v-model="addForm.shiftName" @change="handleRadioChange">
                    <el-radio v-for="option in classify" :key="option.id" :label="option.label">
                      {{ option.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </div>
            <!-- <div class="demo-drawer__footer">
              <el-button type="primary" class=" ml-30" @click="addWork()">
                确定单独排班
              </el-button>
            </div> -->
          </div>

          <div class="batch-add-Work-class">
            <!-- <el-button class="add-btn-class" size="small" type="primary" @click="batchAddDrawer = true">批量排班</el-button> -->
            <el-button class="add-btn-class" size="small" type="primary" @click="madSure">确定排班</el-button>
          </div>

          <el-calendar :value="form.month">
            <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
            <template slot="dateCell" slot-scope="{ date, data }">
              <div class="day-content-class" @click="handleWorkInfo(viewDate[data.day], data)">
                <template v-if="viewDate[data.day]">
                  <div class="header-class">
                    <div class="day-class">
                      {{ data.day.split("-").slice(1).join("-") }}
                    </div>
                    <div class="handle-class">
                      <el-button icon="el-icon-delete" size="mini" circle
                        @click.stop="handleDeleteWork(viewDate[data.day], data)"></el-button>
                    </div>
                  </div>
                  <div class="paiban-class">
                    <div v-for="(dayValue, i) in viewDate[data.day]" :key="i" :class="[
                      'draggable-div' + i,
                      'each-paiban-class',
                      setWorkClass(dayValue.sort),
                      dayValue.shiftName === '早班'
                        ? 'zao-work-class'
                        : dayValue.shiftName === '晚班'
                          ? 'wan-work-class'
                          : 'ye-work-class',
                    ]" :style="{ background: dayValue.color }" draggable="true"
                      @dragstart="handleDragStart($event, dayValue, data.day)"
                      @dragover.prevent="handleDragOver($event)" @dragenter="handleDragEnter($event, dayValue)"
                      @dragend="handleDragEnd()">
                      <i :class="[
                        setIconClass(dayValue.shiftName),
                        'paiban-icon-class',
                      ]"></i>
                      <div class="paiban-name-class">
                        {{ dayValue.shiftName }}
                      </div>
                    </div>
                  </div>
                </template>

                <template v-else>
                  <div class="header-class">
                    <div class="day-class">
                      {{ data.day.split("-").slice(1).join("-") }}
                    </div>
                    <div class="handle-class">
                      <el-button icon="el-icon-edit" size="mini" circle></el-button>
                    </div>
                  </div>
                  <div class="no-work-class">
                    <div class="icon-class"><i class="el-icon-date"></i></div>
                    <div class="tips-class">暂无排班</div>
                  </div>
                </template>
              </div>
            </template>
          </el-calendar>
        </div>
        <!-- 批量排班抽屉弹窗 -->
        <div>
          <el-drawer title="批量排班" :visible.sync="batchAddDrawer" size="40%">
            <div class="demo-drawer__content">
              <el-form :model="batchAddForm">
                <el-form-item label="排班日期" label-width="80px">
                  <el-date-picker v-model="batchAddForm.batchDate" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
                <el-button type="primary" icon="el-icon-plus" circle @click="addDomain"></el-button>
                <el-form-item label-width="80px" v-for="(data, index) in batchAddForm.classData"
                  :label="'排班' + (index + 1) + ':'" :key="data.key">
                  <p></p>
                  <span>班次：</span>
                  <el-radio-group v-model="data.shiftName">
                    <el-radio label="早">早</el-radio>
                    <el-radio label="中">中</el-radio>
                    <el-radio label="晚">晚</el-radio>
                  </el-radio-group>
                  <p></p>
                  <!-- <span>班别：</span>
                      <el-radio-group class="margin-left:80px" v-model="data.groupName">
                        <el-radio label="甲">甲</el-radio>
                        <el-radio label="乙">乙</el-radio>
                        <el-radio label="丙">丙</el-radio>
                      </el-radio-group> -->
                  <el-button class="remove-domain-class" @click.prevent="removeDomain(data)" type="danger"
                    icon="el-icon-delete" circle></el-button>
                </el-form-item>
              </el-form>
            </div>
            <div class="demo-drawer__footer">
              <el-button @click="handleBatchClose">取 消</el-button>
              <el-button type="primary" @click="batchAddWork()">
                确定
              </el-button>
            </div>
          </el-drawer>
        </div>
        <!-- 单独排班 -->
        <div>
          <!-- <el-drawer :title="'【' + hanleDay.day + '】排班'" :visible.sync="drawer" size="40%">
                <div class="add-work-class">
                  <el-button class="add-btn-class" type="primary" @click="innerDrawer = true">添加</el-button> -->
          <el-drawer title="添加排班" :append-to-body="true" :before-close="handleClose" :visible.sync="innerDrawer1">
            <div class="demo-drawer__content">
              <el-form :model="addForm">
                <el-form-item label="班次：" label-width="80px">
                  <!-- <el-radio-group v-model="addForm.shiftName">
                            <el-radio label="早">早</el-radio>
                            <el-radio label="中">中</el-radio>
                            <el-radio label="晚">晚</el-radio>
                          </el-radio-group> -->
                  <el-radio-group v-model="addForm.shiftName" @change="handleRadioChange">
                    <el-radio v-for="option in classify" :key="option.id" :label="option.label">
                      {{ option.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="班别：" label-width="80px">
                  <el-radio-group v-model="addForm.groupName">
                    <el-radio label="甲">甲</el-radio>
                    <el-radio label="乙">乙</el-radio>
                    <el-radio label="丙">丙</el-radio>
                  </el-radio-group>
                </el-form-item> -->
              </el-form>
            </div>
            <div class="demo-drawer__footer">
              <el-button @click="handleClose">取 消</el-button>
              <el-button type="primary" @click="addWork()">
                确定单独排班
              </el-button>
            </div>
          </el-drawer>
        </div>
      </div>
    </el-drawer>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <!-- <el-date-picker class="mb-20" v-model="month" type="month" placeholder="选择月">
      </el-date-picker> -->
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="审核" :visible.sync="examine" width="400px" append-to-body>
      <el-radio-group v-model="examineStatus">
        <el-radio :label="1">审核通过</el-radio>
        <el-radio :label="2">审核不通过</el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changeExamine">确 定</el-button>
        <el-button @click="closeExamine">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import {
  listClassify,
  getClassify,
  delClassify,
  addClassify,
  updateClassify,
  listregionList,
  liststoreList,
  listtechnicianList,
  listclassify,
  addschedule,
  upFrameList,
  exportList,
} from "@/api/system/personnelMatters/arrange";
import { getToken } from "@/utils/auth";

import {
  queryTechnicianListByMonth
} from "@/api/system/personnelMatters/technicianClock";

export default {
  name: "Classify",
  data() {
    return {
      month: "",
      examineStatus: 1,
      examine: false,
      examineId: "",
      classes: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排班分类表格数据
      classifyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        mark: null,
        userName: null,
        beginTime: null,
        endTime: null,
        regionId: null,
        regionName: null,
        storeId: null,
        storeName: null,
      },
      // 表单参数
      region: [], //区域
      store: [], //门店
      technician: [], //人员
      form: {
        area: "",
        postion: "",
        userIds: "",
        month: "",
      },
      // 表单校验
      rules: {},
      viewDate: {
        // "2024-01-01": [
        //   {
        //     // "id": "2024-01-16" + Math.random(1000),
        //     // "ruleName": "三班两运转",
        //     // "shiftName": "早",
        //     // "groupName": "甲",
        //     // "startTime": "2024-01-16 08:30",
        //     // "endTime": "2024-01-16 20:30",
        //     // "isNotHoliday": 0,
        //     // "classId": 1,
        //     // "date": "2024-01-16",
        //     // "sort": 1
        //   },
        // ],
        // "2024-01-02": [
        //   {
        //     "id": "2023-06-21" + Math.random(1000),
        //     "ruleName": "三班两运转",
        //     "shiftName": "中",
        //     "groupName": "乙",
        //     "startTime": "2023-06-20 08:30",
        //     "endTime": "2023-06-20 20:30",
        //     "isNotHoliday": 0,
        //     "classId": 1,
        //     "date": "2023-06-20",
        //     "sort": 2
        //   },
        // ],
        // "2024-02-02": [
        //   {
        //     "id": "2024-01-16" + Math.random(1000),
        //     "ruleName": "三班两运转",
        //     "shiftName": "早",
        //     "groupName": "甲",
        //     "startTime": "2024-01-16 08:30",
        //     "endTime": "2024-01-16 20:30",
        //     "isNotHoliday": 0,
        //     "classId": 1,
        //     "date": "2024-01-16",
        //     "sort": 1
        //   },
        // ],
        // "2024-02-03": [
        //   {
        //     "id": "2023-06-21" + Math.random(1000),
        //     "ruleName": "三班两运转",
        //     "shiftName": "中",
        //     "groupName": "乙",
        //     "startTime": "2023-06-20 08:30",
        //     "endTime": "2023-06-20 20:30",
        //     "isNotHoliday": 0,
        //     "classId": 1,
        //     "date": "2023-06-20",
        //     "sort": 2
        //   },
        // ],
      },
      thisDay: null,
      thisDayWork: null,
      ending: null,
      dragging: null,
      batchAddDrawer: false,
      // 批量添加
      batchAddForm: {
        batchDate: [],
        classData: [
          {
            shiftName: "早",
            groupName: "甲",
          },
        ],
      },
      // 单日添加
      addForm: {
        shiftName: "",
        groupName: "甲",
        sort: 1,
        classId: "",
        color: "",
      },
      drawer: false,
      innerDrawer: false,
      innerDrawer1: false,
      hanleDay: "",
      workInfoList: [],
      classify: [],
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/schedule/importList",
      },
    };
  },
  watch: {
    "addForm.shiftName"(newVal, oldVal) {
      switch (newVal) {
        case "早班":
          this.addForm.sort = 1;
          break;
        case "全天班":
          this.addForm.sort = 2;
          break;
        case "晚班":
          this.addForm.sort = 3;
          break;
        default:
          break;
      }
    },
    // "form.area": {
    //   handler: function (newVal) {
    //     console.log(newVal, '909090')
    //     if (newVal) {
    //       const regionId = newVal;
    //       this.$nextTick(() => {

    //       });
    //     }
    //   },
    // },
    // "form.postion": {
    //   handler: function (newVal) {
    //     if (newVal) {
    //       const belongStoreId = newVal;
    //       this.$nextTick(() => {
    //         listtechnicianList({ belongStoreId }).then((res) => {
    //           console.log(res, 321312);
    //           this.technician = res.data.map((rItem) => {
    //             return {
    //               key: rItem.id,
    //               value: rItem.name,
    //               jobNumber: rItem.jobNumber,
    //             };
    //           });
    //         });
    //       });
    //     }
    //   },
    //   deep: true
    // },
  },
  created() {
    this.getList();
    this.listregionList();
  },
  methods: {
    getStoreList() {
      liststoreList({ regionId: this.form.area }).then((res) => {
        this.store = res.rows.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          };
        });
      });
    },
    getTechnician() {
      // listtechnicianList({ belongStoreId: this.form.postion }).then((res) => {
      //   this.technician = res.data.map((rItem) => {
      //     return {
      //       key: rItem.id,
      //       value: rItem.name,
      //       jobNumber: rItem.jobNumber,
      //     };
      //   });
      // });

      //monthParam  排班月份
      queryTechnicianListByMonth({ belongStoreId: this.form.postion, monthParam: this.form.month }).then((res) => {
        this.technician = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.name,
            jobNumber: rItem.jobNumber,
          };
        });
      });


    },
    changeExamine() { },
    closeExamine() {
      this.examine = false;
    },
    handleExamine(row) {
      console.log(row);
      this.examine = true;
    },
    close() {
      this.viewDate = {};
    },
    handleRadioChange(value) {
      const selectedOption = this.classify.find(
        (option) => option.value === value
      );
      // this.addForm.classId = selectedOption.id;
      // this.addForm.color = selectedOption.color;
      this.addForm = {
        ...this.addForm,
        classId: selectedOption.id,
        color: selectedOption.color,
        shiftName: selectedOption.label,
      };
      console.log("选中的选项为：", selectedOption);
    },
    /** 查询排班分类列表 */
    getList() {
      this.loading = true;
      listClassify(this.queryParams).then((response) => {
        this.classifyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    listregionList() {
      listregionList().then((res) => {
        console.log(res, 121);
        this.region = res.rows.map((rItem) => {
          return {
            value: rItem.id,
            label: rItem.regionName,
          };
        });
      });
    },
    changeRegion(value) {
      console.log("1");
      // console.log(value);
      // const selectedOption = this.region.find((item) => item.value === value);
      // console.log(selectedOption, 123);
      // const selectedKey = selectedOption.label;
      // const selectedValue = selectedOption.value;
      // console.log(`Selected Key: ${selectedKey}`);
      // console.log(`Selected Value: ${selectedValue}`);
      // this.form.regionName = selectedValue;
      // liststoreList({ regionId: value }).then((res) => {
      //   this.store = res.rows.map((rItem) => {
      //     return {
      //       key: rItem.id,
      //       value: rItem.storeName,
      //     };
      //   });
      // });
      // this.form.area = value;
      // if (value) {
      this.form.postion = "";
      this.form.userIds = [];
      this.getStoreList();
      // }
    },
    changeStore(value) {
      // const selectedOption = this.store.find((item) => item.key === value);
      // const selectedKey = selectedOption.key;
      // const selectedValue = selectedOption.value;
      // console.log(`Selected Key: ${selectedKey}`);
      // console.log(`Selected Value: ${selectedValue}`);
      this.form.postion = value;
      this.form.userIds = [];

      this.addForm.shiftName = "";

      this.technician = [];
      this.classify = [];
      if (this.form.postion == "") {
        return;
      }
      upFrameList({ storeId: this.form.postion }).then((res) => {
        this.classify = res.rows.map((rItem) => {
          return {
            label: rItem.name,
            value: rItem.name,
            id: rItem.id,
            color: rItem.colorValue,
          };
        });
      });
      this.getTechnician();
    },
    changeTechnician(value) {
      console.log(value, "00000");
      // const selectedOption = this.technician.find((item) => item.key === value);
      // const selectedKey = selectedOption.key;
      // const selectedValue = selectedOption.jobNumber;
      // console.log(`Selected Key: ${selectedKey}`);
      // console.log(`Selected Value: ${selectedValue}`);
      this.form.userIds = value;
    },
    changeMonth(value) {
      console.log("value-------", value);
      console.log("month-------", this.form.month);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.viewDate = {};
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        mark: null,
        beginTime: null,
        endTime: null,
        regionId: null,
        regionName: null,
        storeId: null,
        storeName: null,
        createTime: null,
        updateTime: null,
        area: "",
        postion: "",
        userIds: [],
        userId: "",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.open = true;
      this.classes = true;
      this.innerDrawer = false;
      this.listregionList();
      this.title = "添加排班分类";
      this.store = []; //门店
      this.classify = [];
      this.technician = []; //人员
      this.addForm.shiftName = "";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const id = row.userId
      this.innerDrawer = false;
      this.addForm.shiftName = "";

      getClassify({ userId: row.userId, month: row.month }).then((response) => {
        this.viewDate = response.data.viewDate;
        this.form = response.data;
        this.form.userIds = [this.form.userId];
        console.log(this.form);
        upFrameList({ storeId: response.data.postion }).then((res) => {
          this.classify = res.rows.map((rItem) => {
            return {
              label: rItem.name,
              value: rItem.name,
              id: rItem.id,
              color: rItem.colorValue,
            };
          });
        });
        this.classes = true;
        this.title = "修改排班分类";
        this.getStoreList();
        this.getTechnician();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row);
      // const ids = row.id || this.ids;
      let _this = this;
      this.$modal
        .confirm("是否确认删除该排班" + row.userName + "的数据项？")
        .then(function () {
          // return delClassify(ids);
          delClassify([
            {
              userId: row.userId,
              month: row.month,
            },
          ]).then((res) => {
            if (res.code == 200) {
              console.log("res", res);
              _this.$modal.msgSuccess("删除成功");
            }
            _this.getList();
          });
        })
        .catch(() => { });
    },
    handletbu(row) {
      console.log(row);
      const userId = row.userId;
      const storeId = row.storeId;
      const regionId = row.regionId;
      const month = row.month;
      this.$modal
        .confirm("是否确认同步该数据项到下个月？")
        .then(function () {
          return addschedule({
            userId: userId,
            storeId: storeId,
            regionId: regionId,
            month: month,
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("同步成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      let obj = {
        userName: this.queryParams.userName || "",
        storeName: this.queryParams.storeName || "",
      };
      this.download(
        "/system/schedule/exportList",
        {
          ...obj,
        },
        `arrange_${new Date().getTime()}.xlsx`
      );
    },

    // 导入按钮操作
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/schedule/exportTempLate ",
        {},
        `排版模版_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    madSure() {
      console.log(this.form, 999);
      this.form.viewDate = this.viewDate;
      addClassify(this.form).then((response) => {
        if (response.code == 200) {
          if (this.form.id && this.form.id != "") {
            this.$modal.msgSuccess("修改成功");
          } else {
            this.$modal.msgSuccess("新增成功");
          }
          this.viewDate = [];
          this.classes = false;
          this.getList();
          console.log(this.form, 777);
        }
      });
    },
    handleDragStart(e, item, thisDay) {
      this.dragging = item;
      this.thisDay = thisDay;
      this.thisDayWork = this.viewDate[thisDay];
    },
    handleDragEnd() {
      if (this.ending.id === this.dragging.id) {
        return;
      }
      let newItems = [...this.thisDayWork];
      const src = newItems.indexOf(this.dragging);
      const dst = newItems.indexOf(this.ending);
      newItems.splice(src, 1, ...newItems.splice(dst, 1, newItems[src]));
      this.$set(this.viewDate, this.thisDay, newItems);
      this.$nextTick(() => {
        this.dragging = null;
        this.ending = null;
      });
      console.log(
        "🚀 ~ file: App.vue:286 ~ handleDragEnd ~ this.viewDate:",
        this.viewDate
      );
    },
    handleDragOver(e) {
      // 首先把div变成可以放置的元素，即重写dragenter/dragover
      e.dataTransfer.dropEffect = "move"; // e.dataTransfer.dropEffect="move";//在dragenter中针对放置目标来设置!
    },
    handleDragEnter(e, item) {
      e.dataTransfer.effectAllowed = "move"; // 为需要移动的元素设置dragstart事件
      this.ending = item;
    },
    // 获取时间范围中的所有日期
    enumerateDaysBetweenDates(startDate, endDate) {
      let daysList = [];
      let SDate = moment(startDate);
      let EDate = moment(endDate);
      daysList.push(SDate.format("YYYY-MM-DD"));
      while (SDate.add(1, "days").isBefore(EDate)) {
        daysList.push(SDate.format("YYYY-MM-DD"));
      }
      daysList.push(EDate.format("YYYY-MM-DD"));
      return daysList;
    },
    setSortValue(value) {
      let sort = 1;
      switch (value) {
        case "早班":
          sort = 1;
          break;
        case "全体班":
          sort = 2;
          break;
        case "晚班":
          sort = 3;
          break;
        default:
          break;
      }
      return sort;
    },
    setWorkClass(value) {
      let classValue = "no-work-class";
      switch (value) {
        case 1:
          classValue = "zao-work-class";
          break;
        case 2:
          classValue = "ye-work-class";
          break;
        case 3:
          classValue = "wan-work-class";
          break;
        default:
          break;
      }
      return classValue;
    },
    setIconClass(value) {
      let classValue = "el-icon-sunrise";
      switch (value) {
        case "早班":
          classValue = "el-icon-sunrise";
          break;
        case "全班":
          classValue = "el-icon-sunny";
          break;
        case "晚":
          classValue = "el-icon-moon";
          break;
        default:
          break;
      }
      return classValue;
    },
    handleDeleteWork(info, data) {
      console.log(info, "info data");
      console.log(data, "info data");
      this.$delete(this.viewDate, data.day);
      // this.deleteRow(info, data);
    },
    // 编辑单日排班
    handleWorkInfo(info, data) {
      console.log(info, "info");
      console.log(data, "data");

      if (
        this.form.area &&
        this.form.postion &&
        this.form.userIds &&
        this.form.userIds.length > 0
      ) {
        this.hanleDay = data;
        this.hanleDay.isSelected = !this.hanleDay.isSelected;

        // this.drawer = true
        this.innerDrawer = true;
        if (info && info.length > 0) {
          // this.addForm.shiftName = info[0].shiftName;
          this.workInfoList = info;
        } else {
          this.workInfoList = [];
        }
        this.addWork();
      } else {
        this.$modal.msgError(`请选择归属区域或归属门店或门店姓名`);
      }
    },
    handleClose() {
      this.innerDrawer = false;
    },
    // 添加单日排班
    addWork() {
      console.log("this.addForm", this.addForm);
      if (!this.addForm.shiftName || !this.addForm.classId) {
        this.$modal.msgError(`请选择班次`);
        return;
      }

      let info = {
        id: this.hanleDay.day + Math.random(1000),
        ruleName: "三班两运转",
        shiftName: this.addForm.shiftName,
        groupName: this.addForm.shiftName,
        startTime: this.hanleDay.day + " 08:30",
        endTime: this.hanleDay.day + " 20:30",
        isNotHoliday: 0,
        classId: 1,
        date: this.hanleDay.day,
        sort: this.addForm.sort,
        classId: this.addForm.classId,
        color: this.addForm.color,
      };

      this.workInfoList = [info];

      this.$set(this.viewDate, this.hanleDay.day, this.workInfoList);
      this.$forceUpdate();
      this.innerDrawer = false;
    },
    // 清除单日排班数据
    deleteRow(row, tableData) {
      let index = row.$index;
      tableData.splice(index, 1);
      if (tableData.length > 0) {
        this.$set(this.viewDate, this.hanleDay.day, tableData);
      } else {
        this.$delete(this.viewDate, this.hanleDay.day);
      }
    },
    addDomain() {
      this.batchAddForm.classData.push({
        shiftName: "早",
        groupName: "甲",
        key: Date.now(),
      });
    },
    removeDomain(item) {
      if (this.batchAddForm.classData.length > 1) {
        var index = this.batchAddForm.classData.indexOf(item);
        if (index !== -1) {
          this.batchAddForm.classData.splice(index, 1);
        }
      } else {
        this.$message({
          message: "请至少安排一个排班",
          type: "error",
        });
      }
    },
    // 批量添加排班数据
    batchAddWork() {
      let dateList = this.batchAddForm.batchDate;
      let classList = this.batchAddForm.classData;
      let list = [];
      if (dateList && dateList.length > 0) {
        list = this.enumerateDaysBetweenDates(dateList[0], dateList[1]);
      }
      list.forEach((item) => {
        let workList = [];
        classList.forEach((work) => {
          let info = {
            id: item + Math.random(1000),
            ruleName: "三班两运转",
            shiftName: work.shiftName,
            groupName: work.groupName,
            startTime: item + " 08:30",
            endTime: item + " 20:30",
            isNotHoliday: 0,
            classId: 1,
            date: item,
            sort: this.setSortValue(work.shiftName),
          };
          workList.push(info);
        });
        this.$set(this.viewDate, item, workList);
      });
      this.batchAddDrawer = false;
    },
    handleBatchClose() {
      this.batchAddDrawer = false;
    },
  },
};
</script>
<style>
#app {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.el-table__fixed-right {
  height: 100% !important;
}

.calender-class {
  height: 100%;
}

.is-selected {
  color: #1989fa;
}

.el-calendar__button-group {
  display: none;
}

.el-calendar__body {
  height: 85vh;
}

.el-calendar-table {
  height: 100%;
}

.el-calendar-day {
  height: 100% !important;
}

.day-content-class {
  height: 100px;
  display: flex;
  flex-direction: column;
}

.header-class {
  flex: 1;
  display: flex;
  align-items: center;
  height: 28px;
  flex-direction: row;
  justify-content: space-between;
}

.day-class {
  flex: 3;
}

.handle-class {
  flex: 1;
}

.paiban-class {
  flex: 4;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: flex-end;
}

.paiban-icon-class {
  font-size: 22px;
  margin: 8px 0 10px 0;
}

.paiban-name-class {
  padding-top: 10px;
}

.each-paiban-class {
  text-align: center;
  max-width: 50px;
  margin: 5px 5px 0 5px;
  border-radius: 5px;
  padding: 0 0 5px 0;
  flex: 1;
}

.zao-work-class {
  /* background-color: #d9ffd9; */
  color: #11be11;
}

.wan-work-class {
  /* background-color: #fff0bd; */
  color: #fccb2c;
}

.ye-work-class {
  /* background-color: #ddeffb; */
  color: #2dabff;
}

.no-work-class {
  text-align: center;
  color: #cacaca;
}

.icon-class {
  font-size: 20px;
  margin-bottom: 20px;
}

/* 侧边弹窗 */
.add-btn-class {
  margin: 10px;
  float: right;
}

.setting {
  display: flex;
}

.ml-30 {
  margin-left: 30px;
}

.mb-20 {
  margin-bottom: 20px;
}
</style>
